<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="page-title">数据同步</h1>
        <div class="breadcrumb-container">
          <router-link to="/" class="link link-hover">首页</router-link>
          <span class="mx-2">/</span>
          <span>数据同步</span>
        </div>
      </div>
      <div class="btn-group">
        <button class="btn btn-primary gap-2" @click="handleSync" :disabled="isSyncing">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z" clip-rule="evenodd" />
          </svg>
          {{ isSyncing ? '同步中...' : '立即同步' }}
        </button>
      </div>
    </div>

    <!-- 同步状态卡片 -->
    <div class="stats shadow mb-6">
      <div class="stat">
        <div class="stat-title">上次同步时间</div>
        <div class="stat-value">{{ lastSyncTime || '暂无' }}</div>
        <div class="stat-desc">{{ lastSyncStatus }}</div>
      </div>
      <div class="stat">
        <div class="stat-title">同步数据量</div>
        <div class="stat-value">{{ syncCount }}</div>
        <div class="stat-desc">条记录</div>
      </div>
      <div class="stat">
        <div class="stat-title">同步成功率</div>
        <div class="stat-value text-success">{{ successRate }}%</div>
        <div class="stat-desc text-success">↗︎ 较上次提升 2%</div>
      </div>
    </div>

    <!-- 同步配置 -->
    <div class="card bg-base-100 shadow-lg mb-6">
      <div class="card-body">
        <h2 class="card-title">同步配置</h2>
        <div class="form-control">
          <label class="label cursor-pointer">
            <span class="label-text">自动同步</span>
            <input type="checkbox" v-model="config.autoSync" class="toggle toggle-primary" />
          </label>
        </div>
        <div class="form-control">
          <label class="label cursor-pointer">
            <span class="label-text">同步间隔（分钟）</span>
            <input
              type="number"
              v-model="config.syncInterval"
              class="input input-bordered w-24"
              min="1"
              :disabled="!config.autoSync"
            />
          </label>
        </div>
        <div class="form-control">
          <label class="label cursor-pointer">
            <span class="label-text">同步失败重试</span>
            <input type="checkbox" v-model="config.retryOnFail" class="toggle toggle-primary" />
          </label>
        </div>
        <div class="form-control">
          <label class="label cursor-pointer">
            <span class="label-text">最大重试次数</span>
            <input
              type="number"
              v-model="config.maxRetries"
              class="input input-bordered w-24"
              min="1"
              :disabled="!config.retryOnFail"
            />
          </label>
        </div>
      </div>
    </div>

    <!-- 同步日志 -->
    <div class="card bg-base-100 shadow-lg">
      <div class="card-body">
        <h2 class="card-title">同步日志</h2>
        <div class="overflow-x-auto">
          <table class="table">
            <thead>
              <tr>
                <th>时间</th>
                <th>类型</th>
                <th>状态</th>
                <th>数据量</th>
                <th>耗时</th>
                <th>详情</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="log in syncLogs" :key="log.id">
                <td>{{ formatDate(log.time) }}</td>
                <td>{{ log.type }}</td>
                <td>
                  <div class="badge" :class="getStatusBadgeClass(log.status)">
                    {{ log.status }}
                  </div>
                </td>
                <td>{{ log.count }}</td>
                <td>{{ log.duration }}s</td>
                <td>
                  <button class="btn btn-ghost btn-xs" @click="showLogDetails(log)">
                    查看
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 日志详情对话框 -->
    <dialog ref="logDetailsDialog" class="modal">
      <div class="modal-box">
        <h3 class="font-bold text-lg">同步日志详情</h3>
        <div class="py-4">
          <pre class="whitespace-pre-wrap">{{ selectedLogDetails }}</pre>
        </div>
        <div class="modal-action">
          <button class="btn" @click="closeLogDetails">关闭</button>
        </div>
      </div>
      <form method="dialog" class="modal-backdrop">
        <button>关闭</button>
      </form>
    </dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { formatDate } from '@/utils/date'
import { useLoadingStore } from '@/stores/loading'
import { useToast } from '@/composables/useToast'

const loadingStore = useLoadingStore()
const toast = useToast()

// 同步状态
const isSyncing = ref(false)
const lastSyncTime = ref('2024-01-01 12:00:00')
const lastSyncStatus = ref('同步成功')
const syncCount = ref(1234)
const successRate = ref(99.8)

// 同步配置
const config = reactive({
  autoSync: true,
  syncInterval: 30,
  retryOnFail: true,
  maxRetries: 3,
})

// 同步日志
const syncLogs = ref([
  {
    id: 1,
    time: '2024-01-01 12:00:00',
    type: '全量同步',
    status: 'success',
    count: 1234,
    duration: 5,
    details: '同步完成，共处理1234条记录',
  },
  {
    id: 2,
    time: '2024-01-01 11:30:00',
    type: '增量同步',
    status: 'warning',
    count: 56,
    duration: 2,
    details: '部分数据同步失败，请检查日志',
  },
  {
    id: 3,
    time: '2024-01-01 11:00:00',
    type: '增量同步',
    status: 'error',
    count: 0,
    duration: 1,
    details: '网络连接失败，请检查网络设置',
  },
])

// 日志详情
const logDetailsDialog = ref<HTMLDialogElement | null>(null)
const selectedLogDetails = ref('')

// 方法
const getStatusBadgeClass = (status: string) => {
  switch (status) {
    case 'success':
      return 'badge-success'
    case 'warning':
      return 'badge-warning'
    case 'error':
      return 'badge-error'
    default:
      return 'badge-ghost'
  }
}

const handleSync = async () => {
  try {
    isSyncing.value = true
    loadingStore.show()
    // TODO: 调用同步API
    await new Promise(resolve => setTimeout(resolve, 2000))
    toast.success('同步成功')
  } catch (error: any) {
    toast.error(error.message || '同步失败')
  } finally {
    isSyncing.value = false
    loadingStore.hide()
  }
}

const showLogDetails = (log: any) => {
  selectedLogDetails.value = log.details
  logDetailsDialog.value?.showModal()
}

const closeLogDetails = () => {
  logDetailsDialog.value?.close()
}
</script>
